<template>
  <div>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="filterForm" label-width="80px" ref="filterForm">
        <el-form-item label="标题" prop="filterTitle">
          <el-input v-model="filterForm.filterTitle" placeholder="模糊匹配房源名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="danger" @click="handleAdd">新增房源</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--表格-->
    <el-table :data="arrList" size="medium" stripe highlight-current-row v-loading="loading" style="width: 100%;"
              @sort-change="handleSort">
      <el-table-column prop="id" label="id" width="100" sortable fixed="left"></el-table-column>
      <el-table-column prop="Community" label="房源小区"></el-table-column>
      <el-table-column prop="titleDesc" label="标题"></el-table-column>
      <el-table-column prop="IndexImagePath" label="主图">
        <template slot-scope="scope">
          <img :src="scope.row.IndexImagePath" @mouseover="showBigPic(scope.row.IndexImagePath)"
               @mouseout="closeBigPic()" width="80"/>
        </template>
      </el-table-column>
      <el-table-column prop="dan_price" label="单价/元/㎡" sortable>
        <template slot-scope="scope">
          <span>{{scope.row.dan_price}}/元/㎡</span>
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="总价/万元" sortable>
        <template slot-scope="scope">
          <span>{{scope.row.totalPrice}}万</span>
        </template>
      </el-table-column>
      <el-table-column prop="AreaStr" label="总面积" sortable>
        <template slot-scope="scope">
          <span>{{scope.row.AreaStr}}㎡</span>
        </template>
      </el-table-column>
      <el-table-column prop="zhungxiu_type" label="装修类型"></el-table-column>
      <!--<el-table-column prop="recommendedReason" label="推荐理由"></el-table-column>-->
      <el-table-column prop="update_time" label="更新时间" sortable></el-table-column>
      <el-table-column prop="type" label="是否为推荐">
        <template slot-scope="scope">
          <span v-if="scope.row.type==1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="jifang" label="户型"></el-table-column>
      <el-table-column prop="chaoxiang" label="朝向"></el-table-column>
      <el-table-column prop="quxian" label="区县"></el-table-column>
      <el-table-column prop="niandai" label="年代"></el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          <el-button style="margin-top: 10px;margin-left: 0" type="success" size="mini"
                     @click="toLookBanner(scope.$index, scope.row)">banner
          </el-button>
          <!--<el-button type="primary" size="mini" @click="getRecommendGoodsList(scope.row)">查看商品</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!--分页工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination layout="sizes, prev, pager, next,total" @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page.sync='page' :page-size="pageSize" :page-sizes="pageSizes" :total="total"
                     style="float:right;">
      </el-pagination>
    </el-col>


    <!--新增页面-->
    <el-dialog :title="editFormTitle" :visible.sync="editFormVisible" :close-on-click-modal="false"
               style="display: none">
      <el-form :model="editForm" label-width="100px" ref="editForm" :rules="editFormRules">
        <el-form-item label="标题" prop="titleDesc">
          <el-input v-model="editForm.titleDesc"></el-input>
        </el-form-item>
        <el-form-item label="小区" prop="Community">
          <el-input v-model="editForm.Community"></el-input>
        </el-form-item>
        <el-form-item label="总价/万元" prop="totalPrice">
          <el-input v-model="editForm.totalPrice"></el-input>
        </el-form-item>
        <el-form-item label="总面积/㎡" prop="AreaStr">
          <el-input @change="changeMj" v-model="editForm.AreaStr"></el-input>
        </el-form-item>
        <el-form-item label="单价/元/㎡" prop="dan_price">
          <el-input v-model="editForm.dan_price"></el-input>
        </el-form-item>
        <el-form-item label="装修类型" prop="zhungxiu_type">
          <el-radio-group v-model="editForm.zhungxiu_type">
            <el-radio class="radio" :label="'毛坯'">毛坯</el-radio>
            <el-radio class="radio" :label="'简装'">简装</el-radio>
            <el-radio class="radio" :label="'中等'">中等</el-radio>
            <el-radio class="radio" :label="'精装'">精装</el-radio>
            <el-radio class="radio" :label="'豪装'">豪装</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否置位推荐" prop="type">
          <el-radio-group v-model="editForm.type">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="户型">
          <el-input v-model="editForm.jifang" placeholder="例如：2室2厅1卫"></el-input>
        </el-form-item>
        <el-form-item label="房源新旧">
          <el-radio-group v-model="editForm.houseNew">
            <el-radio class="radio" :label="'二手房'">二手房</el-radio>
            <el-radio class="radio" :label="'租房'">租房</el-radio>
            <el-radio class="radio" :label="'新房'">新房</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="朝向" prop="chaoxiang">
          <el-input v-model="editForm.chaoxiang" placeholder="例如：朝南"></el-input>
        </el-form-item>
        <el-form-item label="楼层" prop="louceng">
          <el-input v-model="editForm.louceng" placeholder="例如：3-4楼"></el-input>
        </el-form-item>
        <el-form-item label="区县">
          <el-cascader
                  v-model="quxian"
                  :options="options"
                  @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="年代" prop="niandai">
          <el-input v-model="editForm.niandai" placeholder="例如：2012"></el-input>
        </el-form-item>
        <el-form-item label="房源描述" prop="description">
          <div id="editorElem"></div>
        </el-form-item>
        <el-form-item label="视频地址">
          <el-input v-model="editForm.videoUrl"></el-input>
          <el-button style="float: right;margin-top: 20px" type="primary" @click.native="videoUpload">点击上传</el-button>
        </el-form-item>
        <el-form-item label="房源主图">
          <div class="avatar-uploader">
            <div @click="showuploadimg" class="el-upload">
              <img v-if="editForm.IndexImagePath" :src="editForm.IndexImagePath" class="avatar">
              <i v-else="" class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </div>
          <span v-show="false">列表图尺寸:686*388(宽*高)</span>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>

      <el-dialog title="上传视屏" :visible.sync="videoModel" append-to-body width="375px">
        <el-upload
                class="upload-demo"
                :action="uploadVideo"
                multiple
                :limit="1"
                :file-list="fileList"
                :on-success="uploadVideoSuccess"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click.native="videoUrlConfrim">确定</el-button>
        </div>

      </el-dialog>

    </el-dialog>

    <div style="position: fixed;top:35%;left: 40%;z-index: 999" v-show="bigPic != ''">
      <img style="max-width: 400px" :src="bigPic"/>
    </div>

    <el-dialog title="上传图片" :visible.sync="showUploadimg" :close-on-click-modal="false">
      <div class="imgUpwrapper">
        <vueCropper class="uploadwrapper"
                    ref="cropper"
                    :img="uploadImgOption.img"
                    :outputSize="uploadImgOption.size"
                    :outputType="uploadImgOption.outputType"
                    :info="uploadImgOption.info"
                    :canScale="uploadImgOption.canScale"
                    :autoCrop="uploadImgOption.autoCrop"
                    :autoCropWidth="uploadImgOption.autoCropWidth"
                    :autoCropHeight="uploadImgOption.autoCropHeight"
                    :fixed="uploadImgOption.fixed"
                    :fixedNumber="uploadImgOption.fixedNumber"
        ></vueCropper>
        <div class="buttons">

          <label class="btn" for="uploads">选择图片</label>
          <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);"
                 accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event, 1)">

          <!--<div class="show-preview"-->
          <!--:style="{'width': previews.w + 'px', 'height': previews.h + 'px',  'overflow': 'hidden', 'margin': '5px'}">-->
          <!--<div :style="previews.div">-->
          <!--<img :src="previews.url" :style="previews.img">-->
          <!--</div>-->
          <!--</div>-->

        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="finish('blob')" :loading="editLoading">上传图片</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import E from 'wangeditor';
  import {URI_GETHOUSELIST, URI_POSTHOUSEINFO, URI_UPLOAD, URI_DELETECURRENT, URI_UPLOADVIDEO} from 'src/const/uri'
  import VueCropper from 'vue-cropper';

  export default {
    name: "houseList",
    components: {VueCropper},
    data() {
      return {
        /**/
        videoModel: false,
        wangEditor: undefined,
        quxian: [],
        options: [
          {
            value: '孝南',
            label: '孝南',
            children: [{
              value: '孝南城区',
              label: '孝南城区'
            }, {
              value: '孝南周边',
              label: '孝南周边'
            }]
          }],
        uploadImgOption: {
          img: '',
          info: true,
          size: 1,
          outputType: 'png',
          canScale: true,
          autoCrop: true,
          // 只有自动截图开启 宽度高度才生效
          // autoCropWidth:375,
          // autoCropHeight:499,
          // 开启宽度和高度比例
          fixed: true,
          fixedNumber: [1, 1.32960],
          //fixedNumber: [4, 3]
        },
        formData: new FormData(),
        previews: {},
        fileName: '',
        showUploadimg: false,
        /**/
        bigPic: '',
        filterForm: {},
        loading: false,
        codeVisible: false,
        total: 0,
        page: 1,
        pageSize: 10,
        pageSizes: [10, 20, 30, 50, 100],
        arrList: [],
        editForm: {},
        editFormTitle: '',
        editFormVisible: false,
        editLoading: false,
        editFormRules: {
          titleDesc: [
            {required: true, message: '请输入标题', trigger: 'blur'}
          ],
          Community: [
            {required: true, message: '请输入小区', trigger: 'blur'}
          ],
          dan_price: [
            {required: true, message: '请输入单价', trigger: 'blur'}
          ],
          totalPrice: [
            {required: true, message: '请输入总价', trigger: 'blur'}
          ],
          AreaStr: [
            {required: true, message: '输入总面积㎡', trigger: 'blur'}
          ],
          zhungxiu_type: [
            {required: true, message: '选择装修类型', trigger: 'blur'}
          ],
          chaoxiang: [
            {required: true, message: '请输入房源朝向', trigger: 'blur'}
          ],
          louceng: [
            {required: true, message: '请输入房源楼层', trigger: 'blur'}
          ],
          quxian: [
            {required: true, message: '请输入房源区域', trigger: 'blur'}
          ],
          niandai: [
            {required: true, message: '请输入房源年代', trigger: 'blur'}
          ],
          description: [
            {required: true, message: '请输入房源备注描述', trigger: 'blur'}
          ]
        },
        uploadAction: URI_UPLOAD,
        uploadVideo: URI_UPLOADVIDEO,
        local_videoUrl: '',
        fileList: []
      }
    },
    mounted() {
      this.initData();
    },
    watch: {
      editForm(val) {
        // if (val) {
        //   console.log(val.totalPrice);
        //   console.log(val.AreaStr);
        //
        // }
      }
    },
    methods: {
      videoUpload() {
        this.videoModel = true;
      },
      videoUrlConfrim() {
        this.videoModel = false;
        if (this.local_videoUrl) {
          this.editForm.videoUrl = this.local_videoUrl;
        }
        this.fileList = [];
      },
      uploadVideoSuccess(res, file, list) {
        this.local_videoUrl = res.data;
        this.fileList = list;

      },
      changeMj(val) {
        // console.log(this.editForm.totalPrice);
        var total = this.editForm.totalPrice * 10000;
        var areaStr = this.editForm.AreaStr;
        this.editForm.dan_price = Math.round(total / areaStr) + '';
        console.log(this.editForm.dan_price);
        console.log(this.editForm);
      },
      handleChange(value) {
        this.editForm.quxian = value.join('/');
      },
      initData() {
        this.loading = true;
        this.$ajax.get(URI_GETHOUSELIST, {
          page: this.page,
          pageSize: this.pageSize,
          // filter:this.filterForm
          ...this.filterForm
        }, res => {
          this.loading = false;
          this.arrList = res.data;
          this.total = res.total;
        });
      },
      /**/
      showuploadimg() {
        this.showUploadimg = true;
        //console.log(this.editForm.url);
        this.uploadImgOption.img = this.editForm.IndexImagePath;
        //this.uploadImgOption.img= 'http://ofyaji162.bkt.clouddn.com/bg1.jpg';
      },
      uploadImg(e, num) {
        var that = this;
        //上传图片
        // this.option.img
        var file = e.target.files[0];
        //console.log(file);
        if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
          alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
          return false
        }
        var reader = new FileReader()
        reader.onload = (e) => {
          let data
          if (typeof e.target.result === 'object') {
            // 把Array Buffer转化为blob 如果是base64不需要
            data = window.URL.createObjectURL(new Blob([e.target.result]))
          } else {
            data = e.target.result
          }
          if (num === 1) {
            console.log(file.name);
            that.fileName = file.name;
            this.uploadImgOption.img = data
          }
        }
        // 转化为base64
        //reader.readAsDataURL(file)
        // 转化为blob
        reader.readAsArrayBuffer(file)
      },
      finish(type) {
        var that = this;
        if (type === 'blob') {
          this.$refs.cropper.getCropBlob((data) => {
            var blob = data;
            let file = new File([blob], that.fileName || '.jpg');
            that.formData.append('file', file);
            this.$ajax.uploadForm(URI_UPLOAD, {}, res => {
              console.log(res);
              this.showUploadimg = false;
              this.editForm.IndexImagePath = res.data;
              this.uploadImgOption.img = '';
            }, error => {
            }, this.formData);
          })
        } else {
          this.$refs.cropper.getCropData((data) => {
            //test.location.href = data
            console.log(data);
          })
        }
      },
      /**/
      handleSearch() {
        this.page = 1;
        this.initData();
      },
      handleReset() {
        this.filterForm = {};
        this.page = 1;
        this.initData();
      },
      handleAdd() {
        this.editForm = {};
        this.quxian = [];
        if (this.$refs['editForm']) {
          this.$refs['editForm'].clearValidate();
        }
        this.editForm = {IndexImagePath: '', dan_price: '', description: '', videoUrl: ''};
        this.editFormTitle = '新增';
        this.editFormVisible = true;
        this.$nextTick(() => {
          this.handText('');
        });
      },
      handleDelete(index, row) {
        //console.log(row);
        this.$ajax.get(URI_DELETECURRENT, {
          id: row.id
        }, res => {
          this.$message.success(res.data);
          this.initData();
        });
      },
      toLookBanner(index, row) {
        //this.$router.push('/banner')
        this.$router.push('/banner/' + row.id)
      },
      handleSort() {
      },
      handleEdit(index, row) {
        if (this.$refs['editForm']) {
          this.$refs['editForm'].clearValidate();
        }
        this.editForm = Object.assign({}, row);
        this.quxian = this.editForm.quxian.split('/');
        this.editFormTitle = '更新';
        this.editFormVisible = true;
        this.$nextTick(() => {
          this.handText(this.editForm.description)
        });

      },
      handleCurrentChange(page) {
        this.page = page;
        this.initData();
      },
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.page = 1;
        this.initData();
      },
      editSubmit() {
        if (!this.editForm.IndexImagePath) {
          this.$message.error('请上上传房源主图!');
          return;
        }
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$ajax.post(URI_POSTHOUSEINFO, {
              formData: this.editForm,
            }, res => {
              this.$message.success(res.message);
              this.$refs['editForm'].resetFields();
              this.editFormVisible = false;
              this.initData();
            });
          } else {
            this.$message.error('表单验证失败!');
          }
        })

      },
      closeDialog() {
        this.editFormVisible = false;
        this.editForm = {};
      },
      showBigPic(pic) {
        this.bigPic = pic;
      },
      closeBigPic() {
        this.bigPic = '';
      },
      handleAvatarSuccess(res, file) {
        if (res.code === 0) {
          this.editForm.IndexImagePath = res.data;
          // console.log(this.editForm);
          // console.log(this.editForm.IndexImagePath);
        } else {
          this.$message.error('上传失败');
        }

      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 5;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 5MB!');
        }
        return isJPG && isLt2M;
      },
      handText(value) {
        var editor = new E('#editorElem');
        editor.customConfig.zIndex = 100;
        editor.customConfig.colors = ['#ff0000', '#eeece0', '#1c487f', '#4d80bf',
          '#c24f4a', '#8baa4a', '#7b5ba1', '#46acc8', 'yellow', '#ffffff'];
        editor.customConfig.emotions = [
          {
            // tab 的标题
            title: 'emoji',
            // type -> 'emoji' / 'image'
            type: 'emoji',
            // content -> 数组
            content: ['😄', '🎁', '🎉', '😂', '☀', '🎀',
              '😍', '😊', '🏩', '🏠', '🏣', '📞', '☎', '📢', '📣', '⁉', '‼', '❓',
              '❤', '🈶', '㊗', '😃', '🏦', '🏫', '💰']
          },
          {
            // tab 的标题
            title: '默认',
            // type -> 'emoji' / 'image'
            type: 'image',
            // content -> 数组
            content: [
              {
                alt: '[坏笑]',
                src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/4d/2018new_huaixiao_org.png'
              },
              {
                alt: '[舔屏]',
                src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/40/pcmoren_tian_org.png'
              },
              {
                alt: '[嘻嘻]',
                src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/33/2018new_xixi_org.png'
              }
            ]
          }
        ];
        editor.customConfig.onchange = (html) => {
          this.editForm.description = html;
        };
        editor.create();
        editor.txt.html(value);
      }
    }
  }
</script>

<style>
  .toolbar {
    background: #f2f2f2;
    padding: 10px;
    margin: 10px 0px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .upload-demo .el-upload--text {
    border: none;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .el-upload--text {
    width: auto;
    height: auto;
  }

  .avatar {
    width: 300px;
    height: auto;
    display: block;
  }

  /*.avatar-uploader .el-upload {*/
  /*border: 1px dashed #d9d9d9;*/
  /*border-radius: 6px;*/
  /*cursor: pointer;*/
  /*position: relative;*/
  /*overflow: hidden;*/
  /*}*/
  /*.avatar-uploader .el-upload:hover {*/
  /*border-color: #409EFF;*/
  /*}*/
  /*.avatar-uploader-icon {*/
  /*border: 1px dashed #d9d9d9;*/
  /*font-size: 28px;*/
  /*color: #8c939d;*/
  /*height: 178px;*/
  /*line-height: 178px;*/
  /*text-align: center;*/
  /*}*/
  /*.avatar {*/
  /*height: 178px;*/
  /*display: block;*/
  /*}*/

  .imgUpwrapper {
    width: 375px;
    height: 667px;
    margin: 0 auto;
  }

  .imgUpwrapper .btn {
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #fff;
    border: 1px solid #c0ccda;
    color: #1f2d3d;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 20px 10px 0px 0px;
    padding: 9px 15px;
    font-size: 14px;
    border-radius: 4px;
    color: #fff;
    background-color: #50bfff;
    border-color: #50bfff;
    transition: all .2s ease;
    text-decoration: none;
    user-select: none;
  }
</style>